package com.dhcc.core.modules.system.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.constant.state.ScheduleStatus;
import com.dhcc.core.framework.job.ScheduleUtils;
import com.dhcc.core.modules.system.dao.JobMapper;
import com.dhcc.core.modules.system.entity.Job;
import com.dhcc.core.modules.system.service.IJobService;

/**
 * 定时任务表数据服务层接口
 * 
 * @ClassName: JobServiceImpl
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:40:39
 */
@Service("jobService")
public class JobServiceImpl extends BaseServiceImpl<JobMapper, Job> implements IJobService {
    @Autowired
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init() {
        List<Job> jobList = this.selectList(null);
        for (Job job : jobList) {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, job.getId());
            // 如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, job);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, job);
            }
        }
    }

    @Override
    @Transactional
    public void save(Job job) {
        job.setStatus(ScheduleStatus.NORMAL.getValue());
        this.baseMapper.insert(job);
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    @Override
    @Transactional
    public void update(Job job) {
        ScheduleUtils.updateScheduleJob(scheduler, job);
        this.baseMapper.updateById(job);
    }

    @Override
    @Transactional
    public void delete(Long jobId) {
        ScheduleUtils.deleteScheduleJob(scheduler, jobId);
        // 删除数据
        this.baseMapper.deleteById(jobId);
    }

    @Override
    @Transactional
    public void run(Long jobId) {
        ScheduleUtils.run(scheduler, this.selectById(jobId));
    }

    @Override
    @Transactional
    public void pause(Long jobId) {
        ScheduleUtils.pauseJob(scheduler, jobId);
        Job old = this.baseMapper.selectById(jobId);
        old.setStatus(ScheduleStatus.PAUSE.getValue());
        this.baseMapper.updateById(old);
    }

    @Override
    @Transactional
    public void resume(Long jobId) {
        ScheduleUtils.resumeJob(scheduler, jobId);
        Job old = this.baseMapper.selectById(jobId);
        old.setStatus(ScheduleStatus.NORMAL.getValue());
        this.baseMapper.updateById(old);
    }

    @Override
    public List<Job> list(Page<Job> page, Map<String, Object> map) {
        return this.baseMapper.list(page, map);
    }

}